package net.roseboy.classfinal.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class LibUtil {

    public synchronized static void loadLib(String libName) throws IOException,UnsatisfiedLinkError {
        try {

            File root = getTempDir();
            File extractedLibFile = new File(root+"/" +libName);
            extractedLibFile.getParentFile().mkdirs();
            System.out.println("libpath:"+extractedLibFile);

            InputStream in = null;
            FileOutputStream out = null;

            if (!extractedLibFile.exists()) {
                try {
                    String path=libName;
                    in = LibUtil.class.getResourceAsStream(path);
                    System.out.println("lib path:"+path);
                    if (in == null){
                        System.out.println("lib path2:"+"/lib/"+libName);
                        in = LibUtil.class.getResourceAsStream("/lib/"+libName);
                    }

                    out = new FileOutputStream(extractedLibFile);



                    if(in==null){
                        return;
                    }
                    int i;
                    byte[] buf = new byte[1024];
                    while ((i = in.read(buf)) != -1) {
                        out.write(buf, 0, i);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (in != null)
                        in.close();
                    if (out != null)
                        out.close();
                }
            }
            System.load(extractedLibFile.toString());

        }catch (Throwable e){
            if(e instanceof IOException){
                throw (IOException)e;
            }
            if(e instanceof UnsatisfiedLinkError){
                throw (UnsatisfiedLinkError)e;
            }
            e.printStackTrace();
        }
    }

    static File tempDir = null;
    public static File getTempDir() {
        if (tempDir == null) {
            File tmpdir = new File(System.getProperty("java.io.tmpdir"));
            tmpdir.mkdirs();//防止目录不存在
            File f;
            for (int i = 0; i < 1000; i++) {
                f = new File(tmpdir, "javacpp" + System.nanoTime());
                if (f.mkdir()) {
                    tempDir = f;
                    tempDir.deleteOnExit();
                    break;
                }
            }
        }
        return tempDir;
    }
}
